package ATM.service.impl;

import ATM.dao.BaseDAO;
import ATM.dao.UserDAO;
import ATM.dao.impl.UserDAOImpl;
import ATM.pojo.UserDO;
import ATM.service.UserService;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();


    @Override
    public UserDO getByusernameAndPwd(String username, String pwd) {
        return userDAO.getByUsernameAndPwd(username, pwd);

    }

    @Override
    public UserDO getById(String id) {
        return userDAO.getById(id);
    }

    @Override
    public void saveMoney(String id, double blance) {
        UserDO user = userDAO.getById(id);
        user.setCount(user.getCount() + blance);
        userDAO.update(user);
    }


    @Override
    public void getMoney(String id, double blance) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getCount() < blance) {
            throw new Exception("余额不足");
        }
        user.setCount(user.getCount() - blance);
        userDAO.update(user);
    }

    @Override
    public void modifyPwd(String id, String pwd) {
        UserDO user = userDAO.getById(id);
        user.setPassWord(pwd);
        userDAO.update(user);
    }

    @Override
    public void transfer(String id, String otherId, double blance) throws Exception {
        UserDO user = userDAO.getById(id);
        UserDO otherUser = userDAO.getById(otherId);


        if (user.getId().equals(otherUser.getId())) {
            throw new Exception("不能转给自己");

        }
        if (user.getCount() < blance) {
            throw new Exception("余额不足");
        } else {
            user.setCount(user.getCount()-blance);
            otherUser.setCount(otherUser.getCount()+blance);
            userDAO.update(user);
            userDAO.update(otherUser);
            throw new Exception("转账成功");
        }


    }


}
